<template>
  <div class="my-tasks">
    <!-- 任务统计概览 -->
    <div class="task-overview">
      <div class="overview-cards">
        <div class="overview-card">
          <div class="card-icon completed">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ stats.completed }}</div>
            <div class="card-label">已完成</div>
          </div>
        </div>
        
        <div class="overview-card">
          <div class="card-icon in-progress">
            <el-icon><Loading /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ stats.inProgress }}</div>
            <div class="card-label">进行中</div>
          </div>
        </div>
        
        <div class="overview-card">
          <div class="card-icon pending">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ stats.pending }}</div>
            <div class="card-label">待开始</div>
          </div>
        </div>
        
        <div class="overview-card">
          <div class="card-icon total">
            <el-icon><Document /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ stats.total }}</div>
            <div class="card-label">总任务数</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索任务名称..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-right">
        <el-select v-model="statusFilter" placeholder="任务状态" @change="handleFilter">
          <el-option label="全部状态" value="" />
          <el-option label="进行中" value="in_progress" />
          <el-option label="已完成" value="completed" />
          <el-option label="待开始" value="pending" />
        </el-select>

        <el-select v-model="typeFilter" placeholder="任务类型" @change="handleFilter">
          <el-option label="全部类型" value="" />
          <el-option label="视频学习" value="video" />
          <el-option label="实践练习" value="practice" />
          <el-option label="项目实战" value="project" />
          <el-option label="理论学习" value="theory" />
        </el-select>

        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
          <el-option label="最近更新" value="recent" />
          <el-option label="创建时间" value="created" />
          <el-option label="完成进度" value="progress" />
          <el-option label="任务难度" value="difficulty" />
        </el-select>

        <el-button type="primary" icon="Plus" @click="createTask">
          创建任务
        </el-button>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="tasks-container">
      <el-tabs v-model="activeTab" class="task-tabs">
        <!-- 进行中的任务 -->
        <el-tab-pane label="进行中" name="in_progress">
          <div class="tasks-grid">
            <div 
              v-for="task in getTasksByStatus('in_progress')" 
              :key="task.id"
              class="task-card in-progress"
              @click="viewTask(task)"
            >
              <div class="task-header">
                <div class="task-type">
                  <el-tag :type="getTaskTypeColor(task.type)" size="small">
                    {{ getTaskTypeName(task.type) }}
                  </el-tag>
                </div>
                <div class="task-status">
                  <el-icon class="status-icon"><Loading /></el-icon>
                </div>
              </div>
              
              <div class="task-content">
                <h3 class="task-title">{{ task.title }}</h3>
                <p class="task-description">{{ task.description }}</p>
                
                <div class="task-progress">
                  <div class="progress-info">
                    <span>进度：{{ task.progress }}%</span>
                    <span>{{ task.estimatedTime }}分钟</span>
                  </div>
                  <el-progress 
                    :percentage="task.progress" 
                    :show-text="false"
                    :stroke-width="6"
                  />
                </div>
                
                <div class="task-meta">
                  <span class="last-study">上次学习：{{ formatDate(task.lastStudyAt) }}</span>
                </div>
              </div>
              
              <div class="task-footer">
                <el-button type="primary" size="small" @click.stop="continueTask(task)">
                  继续学习
                </el-button>
                <el-button size="small" @click.stop="viewTask(task)">
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 已完成的任务 -->
        <el-tab-pane label="已完成" name="completed">
          <div class="tasks-grid">
            <div 
              v-for="task in getTasksByStatus('completed')" 
              :key="task.id"
              class="task-card completed"
              @click="viewTask(task)"
            >
              <div class="task-header">
                <div class="task-type">
                  <el-tag :type="getTaskTypeColor(task.type)" size="small">
                    {{ getTaskTypeName(task.type) }}
                  </el-tag>
                </div>
                <div class="task-status">
                  <el-icon class="status-icon completed"><CircleCheck /></el-icon>
                </div>
              </div>
              
              <div class="task-content">
                <h3 class="task-title">{{ task.title }}</h3>
                <p class="task-description">{{ task.description }}</p>
                
                <div class="task-completion">
                  <div class="completion-info">
                    <span class="completion-time">完成时间：{{ formatDate(task.completedAt) }}</span>
                    <span class="study-duration">学习时长：{{ task.studyDuration }}分钟</span>
                  </div>
                  
                  <div class="task-score" v-if="task.score">
                    <span class="score-label">得分：</span>
                    <span class="score-value">{{ task.score }}分</span>
                  </div>
                </div>
              </div>
              
              <div class="task-footer">
                <el-button size="small" @click.stop="reviewTask(task)">
                  复习
                </el-button>
                <el-button size="small" @click.stop="viewTask(task)">
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 待开始的任务 -->
        <el-tab-pane label="待开始" name="pending">
          <div class="tasks-grid">
            <div 
              v-for="task in getTasksByStatus('pending')" 
              :key="task.id"
              class="task-card pending"
              @click="viewTask(task)"
            >
              <div class="task-header">
                <div class="task-type">
                  <el-tag :type="getTaskTypeColor(task.type)" size="small">
                    {{ getTaskTypeName(task.type) }}
                  </el-tag>
                </div>
                <div class="task-difficulty">
                  <el-tag :type="getDifficultyColor(task.difficulty)" size="small">
                    {{ task.difficulty }}
                  </el-tag>
                </div>
              </div>
              
              <div class="task-content">
                <h3 class="task-title">{{ task.title }}</h3>
                <p class="task-description">{{ task.description }}</p>
                
                <div class="task-info">
                  <div class="info-item">
                    <el-icon><Clock /></el-icon>
                    <span>预计 {{ task.estimatedTime }} 分钟</span>
                  </div>
                  <div class="info-item">
                    <el-icon><Star /></el-icon>
                    <span>{{ task.difficulty }}</span>
                  </div>
                </div>
              </div>
              
              <div class="task-footer">
                <el-button type="primary" size="small" @click.stop="startTask(task)">
                  开始学习
                </el-button>
                <el-button size="small" @click.stop="viewTask(task)">
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <!-- 空状态 -->
      <div v-if="filteredTasks.length === 0" class="empty-state">
        <EmptyState
          image="/images/empty-tasks.svg"
          title="暂无任务"
          description="您还没有相关的学习任务"
        >
          <el-button type="primary" @click="goToTaskList">
            去选择任务
          </el-button>
        </EmptyState>
      </div>
    </div>

    <!-- 学习统计 -->
    <div class="learning-statistics" v-if="myTasks.length > 0">
      <div class="statistics-header">
        <h3>学习统计</h3>
        <el-button text @click="viewDetailedStats">
          查看详细统计 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      
      <div class="statistics-content">
        <div class="stats-chart">
          <div class="chart-title">本周学习进度</div>
          <div class="chart-placeholder">
            <el-icon><TrendCharts /></el-icon>
            <span>学习进度图表</span>
          </div>
        </div>
        
        <div class="stats-summary">
          <div class="summary-item">
            <div class="summary-label">本周完成任务</div>
            <div class="summary-value">{{ weeklyStats.completedTasks }}个</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">累计学习时间</div>
            <div class="summary-value">{{ weeklyStats.totalTime }}小时</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">平均完成率</div>
            <div class="summary-value">{{ weeklyStats.averageCompletion }}%</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">连续学习天数</div>
            <div class="summary-value">{{ weeklyStats.streakDays }}天</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  CircleCheck, Loading, Clock, Document, Search, Star, 
  ArrowRight, TrendCharts
} from '@element-plus/icons-vue'
import EmptyState from '@/components/global/EmptyState.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const activeTab = ref('in_progress')
const searchKeyword = ref('')
const statusFilter = ref('')
const typeFilter = ref('')
const sortBy = ref('recent')

// 任务统计
const stats = ref({
  completed: 15,
  inProgress: 3,
  pending: 8,
  total: 26
})

// 我的任务数据
const myTasks = ref([
  {
    id: 1,
    title: 'JavaScript基础语法',
    description: '学习JavaScript的基本语法和数据类型',
    type: 'video',
    difficulty: '简单',
    estimatedTime: 30,
    status: 'in_progress',
    progress: 75,
    lastStudyAt: new Date('2024-01-15 14:30:00'),
    createdAt: new Date('2024-01-10 09:00:00')
  },
  {
    id: 2,
    title: 'HTML结构设计',
    description: '掌握HTML标签的使用和页面结构设计',
    type: 'practice',
    difficulty: '简单',
    estimatedTime: 45,
    status: 'completed',
    progress: 100,
    completedAt: new Date('2024-01-14 16:20:00'),
    studyDuration: 42,
    score: 95,
    createdAt: new Date('2024-01-12 10:00:00')
  },
  {
    id: 3,
    title: 'CSS样式布局',
    description: '学习CSS布局技巧和响应式设计',
    type: 'project',
    difficulty: '中等',
    estimatedTime: 60,
    status: 'pending',
    createdAt: new Date('2024-01-16 08:00:00')
  },
  // 添加更多任务数据...
  ...Array.from({ length: 23 }, (_, i) => ({
    id: i + 4,
    title: `学习任务 ${i + 4}`,
    description: `这是第${i + 4}个学习任务的描述`,
    type: ['video', 'practice', 'project', 'theory'][Math.floor(Math.random() * 4)],
    difficulty: ['简单', '中等', '困难'][Math.floor(Math.random() * 3)],
    estimatedTime: Math.floor(Math.random() * 120) + 30,
    status: ['in_progress', 'completed', 'pending'][Math.floor(Math.random() * 3)],
    progress: Math.random() > 0.5 ? Math.floor(Math.random() * 100) : undefined,
    lastStudyAt: Math.random() > 0.5 ? new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000) : undefined,
    completedAt: Math.random() > 0.7 ? new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000) : undefined,
    studyDuration: Math.random() > 0.5 ? Math.floor(Math.random() * 60) + 20 : undefined,
    score: Math.random() > 0.6 ? Math.floor(Math.random() * 40) + 60 : undefined,
    createdAt: new Date(Date.now() - Math.random() * 60 * 24 * 60 * 60 * 1000)
  }))
])

// 学习统计
const weeklyStats = ref({
  completedTasks: 5,
  totalTime: 12.5,
  averageCompletion: 87,
  streakDays: 7
})

// 计算属性
const filteredTasks = computed(() => {
  let filtered = myTasks.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(task => 
      task.title.toLowerCase().includes(keyword) ||
      task.description.toLowerCase().includes(keyword)
    )
  }

  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(task => task.status === statusFilter.value)
  }

  // 类型筛选
  if (typeFilter.value) {
    filtered = filtered.filter(task => task.type === typeFilter.value)
  }

  // 排序
  switch (sortBy.value) {
    case 'created':
      filtered.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
      break
    case 'progress':
      filtered.sort((a, b) => (b.progress || 0) - (a.progress || 0))
      break
    case 'difficulty':
      filtered.sort((a, b) => {
        const order = { '简单': 1, '中等': 2, '困难': 3 }
        return order[a.difficulty] - order[b.difficulty]
      })
      break
    default: // recent
      filtered.sort((a, b) => {
        const aTime = a.lastStudyAt || a.completedAt || a.createdAt
        const bTime = b.lastStudyAt || b.completedAt || b.createdAt
        return new Date(bTime) - new Date(aTime)
      })
  }

  return filtered
})

// 方法
const getTasksByStatus = (status) => {
  return filteredTasks.value.filter(task => task.status === status)
}

const getTaskTypeColor = (type) => {
  const colors = {
    'video': 'primary',
    'practice': 'success',
    'project': 'warning',
    'theory': 'info'
  }
  return colors[type] || 'default'
}

const getTaskTypeName = (type) => {
  const names = {
    'video': '视频学习',
    'practice': '实践练习',
    'project': '项目实战',
    'theory': '理论学习'
  }
  return names[type] || '未知'
}

const getDifficultyColor = (difficulty) => {
  const colors = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return colors[difficulty] || 'info'
}

const formatDate = (date) => {
  if (!date) return '-'
  const now = new Date()
  const diff = now - date
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

const handleSort = () => {
  // 排序逻辑已在计算属性中处理
}

const viewTask = (task) => {
  router.push(`/task/detail/${task.id}`)
}

const continueTask = (task) => {
  router.push(`/task/learn/${task.id}`)
}

const startTask = (task) => {
  router.push(`/task/learn/${task.id}`)
}

const reviewTask = (task) => {
  router.push(`/task/review/${task.id}`)
}

const goToTaskList = () => {
  router.push('/task/list')
}

const createTask = () => {
  router.push('/task/create')
}

const viewDetailedStats = () => {
  ElMessage.info('查看详细统计功能开发中...')
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.my-tasks {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  padding: 20px;
}

.task-overview {
  margin-bottom: 24px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.overview-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  gap: 16px;
  
  .card-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    
    &.completed {
      background: var(--el-color-success-light-9);
      color: var(--el-color-success);
    }
    
    &.in-progress {
      background: var(--el-color-warning-light-9);
      color: var(--el-color-warning);
    }
    
    &.pending {
      background: var(--el-color-info-light-9);
      color: var(--el-color-info);
    }
    
    &.total {
      background: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
    }
  }
  
  .card-content {
    .card-number {
      font-size: 24px;
      font-weight: 700;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .card-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  @media (max-width: 1024px) {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}

.filter-left {
  .el-input {
    width: 300px;
    
    @media (max-width: 1024px) {
      width: 100%;
    }
  }
}

.filter-right {
  display: flex;
  gap: 12px;
  
  @media (max-width: 1024px) {
    flex-wrap: wrap;
  }
  
  .el-select {
    width: 120px;
    
    @media (max-width: 768px) {
      flex: 1;
      min-width: 100px;
    }
  }
}

.tasks-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
}

.task-tabs {
  :deep(.el-tabs__content) {
    padding-top: 20px;
  }
}

.tasks-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.task-card {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  }
  
  &.completed {
    background: var(--el-color-success-light-9);
    border-color: var(--el-color-success-light-5);
  }
  
  &.in-progress {
    background: var(--el-color-warning-light-9);
    border-color: var(--el-color-warning-light-5);
  }
  
  &.pending {
    background: var(--el-fill-color-extra-light);
  }
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.task-status {
  .status-icon {
    font-size: 20px;
    
    &.completed {
      color: var(--el-color-success);
    }
  }
}

.task-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
}

.task-description {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 16px;
  line-height: 1.5;
}

.task-progress {
  margin-bottom: 12px;
  
  .progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.task-completion {
  margin-bottom: 12px;
  
  .completion-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
    margin-bottom: 8px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
  
  .task-score {
    display: flex;
    align-items: center;
    gap: 4px;
    
    .score-label {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
    
    .score-value {
      font-size: 14px;
      font-weight: 600;
      color: var(--el-color-success);
    }
  }
}

.task-info {
  margin-bottom: 12px;
  
  .info-item {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-bottom: 4px;
    font-size: 12px;
    color: var(--el-text-color-placeholder);
    
    .el-icon {
      color: var(--el-color-primary);
    }
  }
}

.task-meta {
  .last-study {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
  }
}

.task-footer {
  display: flex;
  gap: 8px;
  
  .el-button {
    flex: 1;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.learning-statistics {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.statistics-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 40px;
  
  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
  }
}

.stats-chart {
  .chart-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    color: var(--el-text-color-primary);
  }
  
  .chart-placeholder {
    height: 200px;
    background: var(--el-fill-color-extra-light);
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: var(--el-text-color-placeholder);
    
    .el-icon {
      font-size: 32px;
    }
  }
}

.stats-summary {
  .summary-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--el-border-color-extra-light);
    
    &:last-child {
      border-bottom: none;
    }
    
    .summary-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
    
    .summary-value {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-color-primary);
    }
  }
}

@media (max-width: 768px) {
  .overview-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .tasks-grid {
    grid-template-columns: 1fr;
  }
  
  .task-footer {
    flex-direction: column;
    
    .el-button {
      margin-bottom: 8px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>
